/*******************************************************************************
 * Copyright (c) 2011 EclipseDevX.org and others.
 * 
 * All rights reserved. This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution, and is available at:
 * 
 *     http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/

package org.eclipsedevx.core.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPart;

/**
 * 
 * 
 * @author dcarew
 */
public class SelectionUtils {

    private SelectionUtils() {
        
    }

    public static List<Object> getObjects(ISelection selection) {
        if (selection instanceof IStructuredSelection) {
            IStructuredSelection ss = (IStructuredSelection)selection;
            
            return Arrays.asList(ss.toArray());
        } else {
            return Collections.emptyList();
        }
    }
    
    @SuppressWarnings("unchecked")
    public static<T> List<T> getObjects(ISelection selection, Class<T> clazz) {
        List<Object> objects = getObjects(selection);
        List<T> results = new ArrayList<T>();
        
        for (Object object : objects) {
            if (clazz.isInstance(object)) {
                results.add((T)object);
            } else if (object instanceof IAdaptable) {
                Object o = ((IAdaptable)object).getAdapter(clazz);
                
                if (o != null) {
                    results.add((T)o);
                }
            }
        }
        
        return results;
    }

    public static IResource getResourceFor(IWorkbenchPart part) {
        if (part instanceof IEditorPart) {
            IEditorInput input = ((IEditorPart)part).getEditorInput();
            
            if (input != null) {
                return (IResource)input.getAdapter(IResource.class);
            }
        }
        
        return null;
    }
    
}
